﻿// See https://aka.ms/new-console-template for more information

using IocCore.CustomerContainer;
using IocUser.Abstract;
using IocUser.Services;

ICustomerContainerAbstract container = new CustomerContainerImpl();
{
    //注册
    //container.Register<ITestServiceA, ServiceImplA>(lifetimeType: LifetimeType.Singleton); //将ITestServiceA注册到TestServiceA
    //container.Register<ITestServiceB, ServiceImplB>(lifetimeType: LifetimeType.Scope);
    //container.Register<ITestServiceB, ServiceImplB>(shortName: "ServiceB");
    //container.Register<ITestServiceC, ServiceImplC>();
    //container.Register<ITestServiceD, ServiceImplD>(paralist: new object[] { "frank", 666 }, lifetimeType: LifetimeType.Transient);

    //ITestServiceA a = container.Resolve<ITestServiceA>();
    //ITestServiceB b = container.Resolve<ITestServiceB>();
    //ITestServiceD d1 = container.Resolve<ITestServiceD>(); //创建对象交给IOC容器
    //ITestServiceD d2 = container.Resolve<ITestServiceD>();
    //d1.ShowD();
    //Console.WriteLine($"object.ReferenceEquals(d1, d2) = {object.ReferenceEquals(d1, d2)}");

    {
        //生命周期：作用域
        //就是Http请求时，一个请求处理过程中，创建都是同一个实例；不同的请求处理过程中，就是不同的实例；
        //得区分请求，Http请求---Asp.NetCore内置Kestrel，初始化一个容器实例；然后每次来一个Http请求，就clone一个，
        //或者叫创建子容器(包含注册关系)，然后一个请求就一个子容器实例，那么就可以做到请求单例了(其实就是子容器单例)
        //主要可以去做DbContext  Repository
        container.Register<ITestServiceA, ServiceImplA>(lifetimeType: LifetimeType.Scope);
        ITestServiceA a1 = container.Resolve<ITestServiceA>();
        ITestServiceA a2 = container.Resolve<ITestServiceA>();

        Console.WriteLine(object.ReferenceEquals(a1, a2)); //T

        ICustomerContainerAbstract container1 = container.CreateChildContainer();
        ITestServiceA a11 = container1.Resolve<ITestServiceA>();
        ITestServiceA a12 = container1.Resolve<ITestServiceA>();

        ICustomerContainerAbstract container2 = container.CreateChildContainer();
        ITestServiceA a21 = container2.Resolve<ITestServiceA>();
        ITestServiceA a22 = container2.Resolve<ITestServiceA>();

        Console.WriteLine(object.ReferenceEquals(a11, a12)); //T
        Console.WriteLine(object.ReferenceEquals(a21, a22)); //T

        Console.WriteLine(object.ReferenceEquals(a11, a21)); //F
        Console.WriteLine(object.ReferenceEquals(a11, a22)); //F
        Console.WriteLine(object.ReferenceEquals(a12, a21)); //F
        Console.WriteLine(object.ReferenceEquals(a12, a22)); //F
    }
}

Console.ReadKey();
